package com.rjkj.medicalwaste.download;

import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.MimeTypeMap;

import androidx.core.content.FileProvider;

import java.io.File;

/**
 * description |
 * //华为机型是不是没有生成新的下载ID
 * uri | https://ucan.25pp.com/Wandoujia_web_seo_baidu_homepage.apk
 * media_type |application/vnd.android.package-archive
 * local_url |file:///storage/emulated/0/Download/Wandoujia_web_seo_baidu_homepage.apk
 * 06-06 13:35:21.893 1643-2023/system_process I/ActivityManager: START u0 {act=android.intent.action.VIEW dat=content://com.example.keike.downloadmaster
 */
public class DownloadUtil {
    private static DownloadUtil instant;
    private static Context mContext;

    private DownloadUtil() {
    }

    public static DownloadUtil create(Context context) {
        if (instant == null) {
            synchronized (DownloadUtil.class) {
                if (instant == null) {
                    mContext = context;
                    return instant = new DownloadUtil();
                }
            }
        }
        return instant;
    }

    /**
     * @param title   通知栏显示的下载名称
     * @param defName 文件保存的名字和格式
     * @param url     文件下载URL
     * @return
     */
    public long download(String title, String defName, String url) {
        try {
            Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).mkdirs();
            final Uri parse = Uri.parse(url);
            final DownloadManager.Request request = new DownloadManager.Request(parse);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                request.allowScanningByMediaScanner();
                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
            }
            request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI);
            request.setAllowedOverRoaming(false);
            request.setMimeType(MimeTypeMap.getSingleton().getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(url)));
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
            request.setVisibleInDownloadsUi(true);
            request.setTitle(String.valueOf(title));
            //set this to fileName
            url = getFileName(defName, parse);
            request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, url);
            return ((DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE)).enqueue(request);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return -1;
    }

    public long reload(long oldId, String title, String defName, String url) {
        if (oldId != -1) {
            getDownloadMgr().remove(oldId);
        }
        File oldFile = new File(Environment.getExternalStorageDirectory().toString() +
                File.separator + getFileName(defName, Uri.parse(url)));
        if (oldFile.exists()) {
            try {
                oldFile.delete();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return download(title, defName, url);
    }

    public CursorBean querySuccessProcess(String fileName) {
        CursorBean targetBean = null;
        if (TextUtils.isEmpty(fileName)) {
            return targetBean;
        }
        int status_query = DownloadManager.STATUS_PENDING | DownloadManager.STATUS_RUNNING
                | DownloadManager.STATUS_PAUSED | DownloadManager.STATUS_SUCCESSFUL | DownloadManager.STATUS_FAILED;
        Cursor c = null;
        try {
            c = getCursor(true, status_query);
            while (c.moveToNext()) {
                CursorBean queryBean = new CursorBean();
                long downId = c.getLong(c.getColumnIndex(DownloadManager.COLUMN_ID));
                int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
                int reason = c.getInt(c.getColumnIndexOrThrow(DownloadManager.COLUMN_REASON));
                String uri = c.getString(c.getColumnIndex(DownloadManager.COLUMN_URI));
                String title = c.getString(c.getColumnIndex(DownloadManager.COLUMN_TITLE));
                String local_url = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
                String media_type = c.getString(c.getColumnIndex(DownloadManager.COLUMN_MEDIA_TYPE));
                String description = c.getString(c.getColumnIndex(DownloadManager.COLUMN_DESCRIPTION));
                long timeStamp = c.getLong(c.getColumnIndex(DownloadManager.COLUMN_LAST_MODIFIED_TIMESTAMP));

                Log.d("download-kk", "description | " + description + "\r\n"
                        + "uri | " + uri + "\r\n"
                        + "media_type |" + media_type + "\r\n"
                        + "local_url |" + local_url + "\r\n");
                String filePath = getDownloadFile(c);
                queryBean.setId(downId);
                queryBean.setTitle(title);
                queryBean.setFile(filePath);
                queryBean.setStatus(status);
                queryBean.setTimeStamp(timeStamp);
                if (!TextUtils.isEmpty(filePath) && fileName.contains(fileName)) {
                    if (reason != DownloadManager.PAUSED_WAITING_TO_RETRY
                            && reason != DownloadManager.STATUS_FAILED
                            && reason != DownloadManager.STATUS_PAUSED) {
                        if (null == targetBean) {
                            targetBean = new CursorBean();
                        }
                        if (timeStamp > targetBean.getTimeStamp()) {
                            if (targetBean != null && targetBean.getId() != 0) {
                                getDownloadMgr().remove(downId);
                            }
                            targetBean = queryBean;
                        }
                    } else {
                        try {
                            getDownloadMgr().remove(downId);
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    }
                }
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            if (c != null)
                try {
                    c.close();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
        }
        return targetBean;
    }
    public CursorBean queryProcess(String fileName) {
        CursorBean targetBean = null;
        if (TextUtils.isEmpty(fileName)) {
            return targetBean;
        }
        int status_query = DownloadManager.STATUS_PENDING | DownloadManager.STATUS_RUNNING
                | DownloadManager.STATUS_PAUSED | DownloadManager.STATUS_SUCCESSFUL | DownloadManager.STATUS_FAILED;
        Cursor c = null;
        try {
            c = getCursor(true, status_query);
            while (c.moveToNext()) {
                CursorBean queryBean = new CursorBean();
                long downId = c.getLong(c.getColumnIndex(DownloadManager.COLUMN_ID));
                int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
                int reason = c.getInt(c.getColumnIndexOrThrow(DownloadManager.COLUMN_REASON));
                String uri = c.getString(c.getColumnIndex(DownloadManager.COLUMN_URI));
                String title = c.getString(c.getColumnIndex(DownloadManager.COLUMN_TITLE));
                String local_url = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
                String media_type = c.getString(c.getColumnIndex(DownloadManager.COLUMN_MEDIA_TYPE));
                String description = c.getString(c.getColumnIndex(DownloadManager.COLUMN_DESCRIPTION));
                long timeStamp = c.getLong(c.getColumnIndex(DownloadManager.COLUMN_LAST_MODIFIED_TIMESTAMP));

                Log.d("download-kk", "description | " + description + "\r\n"
                        + "uri | " + uri + "\r\n"
                        + "media_type |" + media_type + "\r\n"
                        + "local_url |" + local_url + "\r\n");
                String filePath = getDownloadFile(c);
                queryBean.setId(downId);
                queryBean.setTitle(title);
                queryBean.setFile(filePath);
                queryBean.setStatus(status);
                queryBean.setTimeStamp(timeStamp);
                if (!TextUtils.isEmpty(filePath) && fileName.equals(title)) {
                    if (reason != DownloadManager.PAUSED_WAITING_TO_RETRY
                            && reason != DownloadManager.STATUS_FAILED
                            && reason != DownloadManager.STATUS_PAUSED) {
                        if (null == targetBean) {
                            targetBean = new CursorBean();
                        }
                        if (timeStamp > targetBean.getTimeStamp()) {
                            if (targetBean != null && targetBean.getId() != 0) {
                                getDownloadMgr().remove(downId);
                            }
                            targetBean = queryBean;
                        }
                    } else {
                        try {
                            getDownloadMgr().remove(downId);
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    }
                }
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            if (c != null)
                try {
                    c.close();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
        }
        return targetBean;
    }

    /**
     * @param status true| 状态查询   id:状态   false|ID查询    id:downloadId
     * @param id
     * @return
     */
    public Cursor getCursor(boolean status, long id) {
        DownloadManager downMgr = getDownloadMgr();
        DownloadManager.Query query = new DownloadManager.Query();
        if (status) {
            query.setFilterByStatus((int) id);
        } else {
            query.setFilterById(id);
        }
        return downMgr.query(query);
    }


    public void install(String filePath, String authority) {
        if (filePath.endsWith(".apk")) {
            if (Build.VERSION.SDK_INT >= 24) {
                //判读版本是否在7.0以上
                File file = new File(filePath);
                Uri apkUri = FileProvider.getUriForFile(mContext, authority, file);
                Intent install = new Intent(Intent.ACTION_VIEW);
                // 由于没有在Activity环境下启动Activity,设置下面的标签
                install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                //添加这一句表示对目标应用临时授权该Uri所代表的文件
                install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                install.setDataAndType(apkUri, "application/vnd.android.package-archive");
                mContext.startActivity(install);
            } else {
                Intent install = new Intent(Intent.ACTION_VIEW);
                install.setDataAndType(Uri.fromFile(new File(filePath)),
                        "application/vnd.android.package-archive");
                install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                mContext.startActivity(install);
            }
        }
//        if (mContext != null) {
//            mContext.sendBroadcast(new Intent("filter_action_install"));
//        }
    }


    public boolean canDownloadState(Context ctx) {
        try {
            int state = ctx.getPackageManager().getApplicationEnabledSetting("com.android.providers.downloads");
            if (state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED
                    || state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER
                    || state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }


    /**
     * "*****.apk"
     *
     * @param defName 默认文件名字
     * @param url     默认下载url
     * @return 文件保存名字
     */
    public String getFileName(String defName, String url) {
        return getFileName(defName, Uri.parse(url));
    }

    private String getFileName(String defName, final Uri uri) {
        String s = null;
        if (uri != null) {
            final String lastPathSegment = uri.getLastPathSegment();
            if (lastPathSegment == null) {
                s = defName;
            } else {
                s = lastPathSegment;
                if (!lastPathSegment.endsWith(".apk")) {
                    return lastPathSegment + ".apk";
                }
            }
        }
        return s;
    }


    /**
     * 返回系统下载管理器
     *
     * @return
     */
    public DownloadManager getDownloadMgr() {
        return (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
    }

    public void downloadByWeb(String url) {
        Intent intent = new Intent();
        intent.setAction("android.intent.action.VIEW");
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        Uri content_url = Uri.parse(url);
        intent.setData(content_url);
        mContext.startActivity(intent);
    }

    /**
     * @param cursor :downloadId 获取到的查询游标
     * @return filePath  :文件路径
     * M版本上下的兼容
     */
    public String getDownloadFile(Cursor cursor) {
        String filePath = "";
        String local_url = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
            if (!TextUtils.isEmpty(local_url)) {
                filePath = Uri.parse(local_url).getPath();
            }
        } else {
            filePath = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME));
        }
        return filePath;
    }


}
